package net.server.handler;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import ui.ChatWindow;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import core.ChatNode;
import db.Mapper;


public class SendMessageHandler implements HttpHandler
{
	private ChatNode node;
	
	public SendMessageHandler(ChatNode node)
	{
		this.node = node;
	}
	
	@Override
	public void handle(HttpExchange t) throws IOException
	{
		@SuppressWarnings("unchecked")
		Map<String, String> params = (Map<String, String>)t.getAttribute("parameters");
		
		String response = "OK";
		t.sendResponseHeaders(200, response.length());
		OutputStream os = t.getResponseBody();
		os.write(response.getBytes());
		os.close();
		
		//ui.appendChat("DEBUG: saabus request");
		if(params.containsKey("myname") && params.containsKey("myip") && params.containsKey("message"))
		{
			String fromAddress = t.getRemoteAddress().getAddress().getHostAddress();
			node.getMainWindow().appendText(fromAddress + " > " + t.getRequestURI());
			
			String remoteName = params.get("myname");
			String remoteAddress = params.get("myip");
			String message = params.get("message");
			//String ttl = params.get("ttl");
			
			
			Mapper userbase = node.getUserBase();
			if(!userbase.containsName(remoteName))
			{
				userbase.addPeer(remoteName, remoteAddress);
				node.getMainWindow().setUserList(userbase.getPeersArray());
			}
			
			if(node.getLoginTask().isDone())
			{
				//uuenda UI-d
				ChatWindow targetWindow = node.getChatWindow(remoteName + "@" + remoteAddress);
				targetWindow.appendMessage(remoteName, message);
			}
			
		}

	}

}
